package se480.paf.filters.impl;

import java.util.ArrayList;

import org.apache.log4j.Logger;

import se480.paf.filters.ActiveFilter;
import se480.paf.pipes.Item;
import se480.paf.pipes.Pipe;
import se480.paf.pipes.impl.Queue;

/**
 * This filter parses file lines into words
 * 
 * Input:  List<String> of lines
 * Output:  List<String> of words
 * 
 * @author mmichalak
 *
 */
public class Lines2WordsFilter implements ActiveFilter {
	
	static Logger logger = Logger.getLogger("Lines2WordsFilter");
	
	String name = "Lines2WordsFilter";
	int msSleep = 2000; // Default Thread sleep time
	
	public Pipe<Item> inPipe;
	public Pipe<Item> outPipe;

	
	@Override
	public void run() {
		try {
		      int i = 0;
		      while (true) {
		    	 if (!inPipe.isEmpty()) {
		    		 Item item = inPipe.removeItem();
		    		 process(item);
		    	 }
		    	  
		    	 logger.debug(name + " wake: " + i++);
		         Thread.sleep(msSleep);

		      }
      } catch (InterruptedException e) {
    	  //logger.debug(name + " interrupted.");
      }
     logger.debug(name + " exiting.");

	}

	@Override
	public void process(Item item) {
		long startTime = System.currentTimeMillis();
		 ArrayList<String> lines = (ArrayList<String>)item.getItem();
		 logger.debug(name + " picked up " + item.getName());
		 
		int N = 0;
		ArrayList words = new ArrayList();
		for (String line : lines) {
			String[] lineWords = line.split(" ");
			//logger.debug( line);
			for (String s : lineWords)
				words.add(s);
			N++;
		} 

	    item.setItem(words);
	    long endTime = System.currentTimeMillis();
	    item.addExecuteTimes(name + " - " + (endTime - startTime));
	    
	    outPipe.addItem(item);
	}


	@Override
	public void setInPipe(Pipe<Item> pipe) {
		this.inPipe = pipe;
	}

	@Override
	public void setOutPipe(Pipe<Item> pipe) {
		this.outPipe = pipe;
	}


	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public void setSleep(int msSleep) {
		this.msSleep = msSleep;
	}

	@Override
	public int getSleep() {
		return this.msSleep;
	}

	@Override
	public Pipe<Item> getInPipe() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Pipe<Item> getOutPipe() {
		// TODO Auto-generated method stub
		return null;
	}

}
